/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-07-04 09:48:17
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-07-04 10:44:34
 * @FilePath: /lesson/lesson_net/blog_test/UdpServer.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>

#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>
#include <ctime>
#include <cstdarg>
#include <fstream>
#include <cstring>
#include <pthread.h>

class UdpServer
{
public:
    bool InitServer()
    {
        // 1、创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            std::cout << "create socket fail" << std::endl;
            exit(-1);
        }
        std::cout << "create socket success,sockfd: " << _sockfd << std::endl;
        return true;

        // 重点：在bind之前，必须现将网络属性信息填充到 struct sockaddr_in结构体中！
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        // 2、绑定

        if (bind(_sockfd, (struct sockaddr *)&local, sizeof(sockaddr)) < 0)
        {
            std::cout << "bind fail " << std::endl;
            exit(-1);
        }
        std::cout << "bind success" << std::endl;

        return true;
    }

    UdpServer(std::string ip, int port)
        : _ip(ip), _port(port), _sockfd(-1)
    {
    }

    ~UdpServer()
    {
        if (_sockfd >= 0)
        {
            close(_sockfd);
        }
    }

private:
    int _sockfd;

    std::string _ip;
    int _port;
};